<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <el-col :span="isHide ? 1 : 6" :xs="24" class="relative">
        <div class="app-container-tree-border">
          <project-tree-select-inner class="cd-mb8" :projectId="projectId" @changeProject="changeProject" />
          <el-tree :data="treeList" :props="defaultProps" ref="tree" node-key="id" highlight-current
            @node-click="handleNodeClick" default-expand-all :current-node-key="query.qsId">
            <div slot-scope="{node, data}" class="custom-tree-node" :title="node.label" v-text="node.label"></div>
          </el-tree>
          <div class="tree-hide-button iconfont" :class="isHide ? 'icon-xiangyou' : 'icon-xiangzuo'"
            @click="() => { isHide = !isHide }">
          </div>
        </div>
      </el-col>
      <el-col :span="isHide ? 23 : 18" :xs="24">
        <div class="app-container-table-border">
          <el-row v-if="queryParams.qsId && queryParams.bdId" :gutter="10"
            class="mb8 cd-pr8 top-right-btn small-line-height">
            <el-col :span="1.5">
              <el-button type="primary" plain size="mini" @click="onUploadFile">附件管理</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain size="mini" @click="handleExport">导出</el-button>
            </el-col>
            <el-col :span="1.5" v-if="reportStatus == '00' || reportStatus == '33'">
              <el-button type="primary" size="mini" plain @click="onExamine">发起审批</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="text" size="mini" :disabled="reportStatus == '00'" @click="handleProcess()">
                {{ reportStatusFormat() }}
              </el-button>
            </el-col>
          </el-row>
          <el-table v-if="queryParams.qsId && queryParams.bdId" class="report-table" border stripe :data="dataList"
            :summary-method="getSummaries" show-summary :max-height="tableHeight">
            <el-table-column type="index" fixed width="50" align="center" label="序号">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="name" fixed header-align="center" label="站点名称" min-width="180"
              show-overflow-tooltip />
            <el-table-column prop="beiazmc" header-align="center" label="备案证名称" min-width="180" show-overflow-tooltip />
            <el-table-column prop="jianscj" header-align="center" label="建设场景" min-width="120" show-overflow-tooltip />
            <!--            <el-table-column prop="jiansrl" header-align="center" label="备案容量(千瓦)" min-width="120" show-overflow-tooltip />-->
            <el-table-column prop="jiansrl" header-align="center" align="right" label="实际建设容量(千瓦)" min-width="135"
              show-overflow-tooltip />
            <el-table-column prop="danwzj" header-align="center" align="right" label="单瓦造价(元/瓦)" min-width="115"
              show-overflow-tooltip />
            <el-table-column prop="chgPrice" header-align="center" align="right" label="变动后价格(元/瓦)" min-width="125"
              show-overflow-tooltip />
            <el-table-column prop="danzdzj" header-align="center" align="right" label="单站点总价(元)" min-width="140"
              show-overflow-tooltip />
            <el-table-column prop="yizfyfk" header-align="center" align="right" label="已支付预付款(元)" min-width="110"
              show-overflow-tooltip />
            <el-table-column prop="leijkcyfk" header-align="center" align="right" label="累计扣除预付款(元)" min-width="120"
              show-overflow-tooltip />
            <el-table-column prop="benckkje" header-align="center" align="right" label="本次扣款(奖励基金)金额(元)" min-width="120"
              show-overflow-tooltip />
            <el-table-column prop="leijkkje" header-align="center" align="right" label="累计扣款(奖励基金)金额(元)" min-width="120"
              show-overflow-tooltip />
            <el-table-column prop="jiezscljfkje" header-align="center" align="right" label="截止上次累计付款金额(元)"
              min-width="120" show-overflow-tooltip />
            <el-table-column prop="bencfkje" header-align="center" align="right" label="本次付款金额(元)" min-width="120"
              show-overflow-tooltip />
            <el-table-column prop="jiezbcljfkje" header-align="center" align="right" label="截止本次累计付款金额(元)"
              min-width="120" show-overflow-tooltip />
            <el-table-column prop="fukbl" header-align="center" align="right" label="付款比例" min-width="120"
              show-overflow-tooltip />
            <el-table-column align="center" label="附件" width="100">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-paperclip"
                  @click="onViewFile(scope.row)">附件查看</el-button>
              </template>
            </el-table-column>

          </el-table>
          <el-empty v-else description="请选择期数..." :image-size="250"></el-empty>
          <!-- <img src="./1.png" alt="报表" style="width: 100%;" /> -->
        </div>
      </el-col>
    </el-row>
    <file-view ref="fileViewRef" :moduleKey="'bsSettle'" />
    <file-upload-view ref="fileUploadViewRef" :moduleKey="'reportForm'" :disabled="!canOperation()" />
    <!--    <file-upload-view ref="fileUploadViewRef" :moduleKey="'reportForm'" :candelete="!canOperation()" />-->
    <examine-and-approve ref="examineAndApproveRef" @callBack="getReportStatus" />

  </div>
</template>

<script>
import { queryBdQsTree } from "@/api/base/bsBd";
import { queryReportInfo, queryReportStatus, checkReport } from "@/api/cm/reportForm";
import { mapGetters } from "vuex";
import FileView from './file-view.vue';
import ExamineAndApprove from './examine-and-approve.vue';
import decimal from "@/utils/big-decimal";
import FileUploadView from '@/components/FileUpload/FileUploadView.vue';


export default {
  name: "ReportForm",
  dicts: ['report_status'],
  components: {
    FileView,
    ExamineAndApprove,
    FileUploadView
  },
  data () {
    return {
      isHide: false,
      treeList: [],
      treeInfo: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 期数表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        qsId: undefined,
        bdId: undefined,
      },
      projectId: undefined,
      reportStatus: '',
      reportInfo: {},
      tableHeight: document.documentElement.scrollHeight - 170,
      query: { projectId: undefined, bdId: undefined, qsId: undefined }
    };
  },
  // 监听顶部全局下拉
  computed: {
    ...mapGetters(["sysProjectId", "sysProjectList"])
  },
  watch: {
    $route: {
      handler: function (route) {
        this.query.projectId = route.query && route.query.projectId;
        this.query.bdId = route.query && route.query.bdId;
        this.query.qsId = route.query && route.query.qsId;
        setTimeout(() => {
          this.changeProject(this.query.projectId);
        }, 1000);
      },
      immediate: true
    },
    sysProjectId (newVal, oldVal) {
      // 系统顶部选中项目变化
      this.changeProject(newVal);
    }
  },
  created () {
    if (!(this.$route.query && this.$route.query.projectId)) {
      this.changeProject();
    }
  },
  methods: {
    changeProject (projectId = this.sysProjectId) {
      this.projectId = projectId;
      this.projectChangeResetQuery();
      this.getQsTree();
    },
    getQsTree () {
      queryBdQsTree({ projectId: this.projectId }).then(response => {
        this.treeList = response.data;
        if (this.query.bdId && this.query.qsId) {
          this.setTreeNode();
        }
      });
    },
    // 选中树节点
    setTreeNode () {
      this.queryParams.qsId = this.query.qsId;
      this.queryParams.bdId = this.query.bdId;
      this.getReportStatus();
      this.getTableList();
    },
    handleNodeClick (data) {
      if (data.type == 'qs') {
        this.treeInfo = data;
        this.queryParams.qsId = data.id;
        this.queryParams.bdId = data.parentId;
        this.getReportStatus();
        this.getTableList();
      }
    },
    projectChangeResetQuery () {
      this.queryParams = {
        qsId: undefined,
        bdId: undefined,
      };
      this.dataList = [];
    },
    // 获取报表状态
    getReportStatus () {
      const query = {
        bdId: this.queryParams.bdId,
        qsId: this.queryParams.qsId
      };
      queryReportStatus(query).then(res => {
        const info = res.data;
        this.reportInfo = info;
        this.reportStatus = info.status;
      });
    },
    getTableList () {
      queryReportInfo(this.queryParams).then(res => {
        this.dataList = res.data;
        //实际建设容量瓦转千瓦；
        // this.dataList.forEach(e => e.jiansrl = decimal.divide(e.jiansrl, 1000, 4));
      });
    },
    getSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '合计';
          return;
        }
        if (index >= 7 && index <= 14) {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return decimal.add(prev, curr);
              } else {
                return decimal.round(prev);
              }
            }, 0);
            sums[index] += '';
          } else {
            sums[index] = '';
          }
        }
      });

      return sums;
    },
    // 状态字典翻译
    reportStatusFormat () {
      return this.selectDictLabel(this.dict.type.report_status, this.reportStatus);
    },
    // 附件上传
    onUploadFile () {
      const info = {
        businessId: this.queryParams.bdId,
        subBusinessId: this.queryParams.qsId,
      };
      this.$refs.fileUploadViewRef.init(info);
    },
    // 附件查看
    onViewFile (row) {
      const info = {
        businessId: row.id,
        subBusinessId: this.queryParams.qsId,
      };
      this.$refs.fileViewRef.init(info);
    },

    // 是否可操作
    canOperation () {
      return this.reportStatus == '00' || this.reportStatus == '33';
    },

    /** 导出按钮操作 */
    handleExport () {
      this.download('cm/bdQsCount/exportReport', {
        ...this.queryParams
      }, `报表_${new Date().getTime()}.xlsx`);
    },
    /** 发起审批 */
    async onExamine () {
      try {
        // const query = {
        //   bdId: this.queryParams.bdId,
        //   qsId: this.queryParams.qsId
        // };
        const query = this.dataList;
        //校验上期报表是否已审批，否则不允许发起审批；
        //校验各站点付款比例对应的工序报验是否已审批完成，没审批完成的不允许发起；
        await checkReport(query);
        const projectInfo = this.sysProjectList.find(item => item.projectId == this.projectId);
        const info = {
          projectId: this.projectId,
          projectName: projectInfo.projectName,
          bdId: this.queryParams.bdId,
          qsId: this.queryParams.qsId,
          qsName: this.treeInfo.label,
          id: this.reportInfo.id
        };
        this.$refs.examineAndApproveRef.init(info);
      } catch (error) {

      }
    },
    // 跳转到审批处理页面
    handleProcess () {
      const info = this.reportInfo;
      if (!info.procInsId) {
        this.$message.warning("流程信息不存在！");
        return;
      }
      const processed = this.reportStatus == '11' && info.currApproval;
      this.$router.push({
        path: '/workflow/process/detail/' + info.procInsId,
        query: {
          taskId: info.taskId,
          processed: processed
        }
      });
    },
  }
};
</script>
<style lang="scss" scoped>
::v-deep .report-table {
  .el-table__header-wrapper th {
    height: 22px !important;
  }
}
</style>
